from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.utils import timezone

class UserManager(BaseUserManager):
    def create_user(self, username, password=None, **extra_fields):
        if not username:
            raise ValueError('The Username field must be set')
        user = self.model(username=username, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user
    
    def create_superuser(self, username, password=None, **extra_fields):
        # 设置管理员权限字段
        extra_fields.setdefault('user_type', 'admin')
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)
        
        return self.create_user(username, password, **extra_fields)

class User(AbstractBaseUser, PermissionsMixin):
    # 用户类型
    USER_TYPE_CHOICES = (
        ('admin', '管理员'),
        ('user', '普通用户'),
    )
    
    # 基础信息
    username = models.CharField(max_length=150, unique=True, verbose_name='用户名')
    # 个人信息
    avatar = models.ImageField(upload_to='avatars/', blank=True, null=True, verbose_name='头像')
    # 权限字段
    user_type = models.CharField(max_length=10, choices=USER_TYPE_CHOICES, default='user', verbose_name='用户类型')
    is_staff = models.BooleanField(default=False, help_text='是否可以访问管理后台')
    is_active = models.BooleanField(default=True, help_text='是否激活用户')
    is_superuser = models.BooleanField(default=False, help_text='是否为超级用户')
    # 时间字段
    date_joined = models.DateTimeField(default=timezone.now, verbose_name='注册时间')
    last_login = models.DateTimeField(blank=True, null=True, verbose_name='最后登录时间')
    
    objects = UserManager()
    
    USERNAME_FIELD = 'username'
    
    class Meta:
        verbose_name = '用户'
        verbose_name_plural = '用户'
        ordering = ['-date_joined']
    
    def __str__(self):
        return self.username
    
    # 登录后跳转需要
    @property
    def is_admin_user(self):
        """判断是否为管理员 - 用于登录后跳转"""
        return self.user_type == 'admin'